package com.zqsoft.utils;


import java.io.*;
import java.util.*;

/**
 * 文件读写操作
 * @author 周翔
 */
public class FileUtils {

    /**
     * 读取文件，将文件中的每一行解析成一个字符串，并且将多行记录加入到List集合对象中
     * @param fileName
     * @return
     */
    public static List<String> readFile(String fileName) {
        List<String> allLine = new ArrayList<String>();
        BufferedReader reader = null;
        File file = new File(fileName);
        // 检查文件是否存在，如果不存在则创建它
        if (!file.exists()) {
            try {
                file.createNewFile(); // 创建新文件
            } catch (IOException ex) {
                ex.printStackTrace();             
            }
        }
        try {
            reader = new BufferedReader(new FileReader(new File(fileName)));
            String str = null;
            while ((str = reader.readLine()) != null) {
                allLine.add(str);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return allLine;
    }

    /**
     * 将字符串写入文本文件中，采用的方式为覆盖旧文件
     * @param fileName
     * @param str
     */
    public static void writeFile(String fileName, String str) {
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(new File(fileName)));
            writer.write(str);
            writer.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

}